<route lang="json5" type="page">
  {
    layout: 'default',
    style: {
      navigationStyle: 'custom',
    },
  }
</route>

<script setup lang="ts">
import type { Role } from '@/store/user'

import { useUserStore } from '@/store/user'

const userStore = useUserStore()

// 表单数据
const form = reactive({
  phone: '',
  password: '',
  verifyCode: '',
})

// 当前登录方式：'login' | 'register'
const currentMode = ref('login')

// 验证码倒计时
const countdown = ref(0)
const canSendCode = ref(true)
const role = ref<Role>('user')

// 同意服务条款
const agree = ref(false)

// 同意服务条款
function handleAgreeChange(value: { value: boolean }) {
  console.log('handleAgreeChange', value)
  agree.value = value.value
}

// 切换登录/注册模式
function switchMode(mode: 'login' | 'register') {
  currentMode.value = mode
}

// 发送验证码
async function sendVerifyCode() {
  if (!form.phone) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none',
    })
    return
  }

  if (!canSendCode.value)
    return

  try {
    // 这里应该调用实际的发送验证码接口
    console.log('发送验证码到:', form.phone)

    // 开始倒计时
    countdown.value = 60
    canSendCode.value = false

    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
        canSendCode.value = true
      }
    }, 1000)

    uni.showToast({
      title: '验证码已发送',
      icon: 'success',
    })
  }
  catch (error) {
    console.error('发送验证码失败:', error)
    uni.showToast({
      title: '发送失败，请重试',
      icon: 'none',
    })
  }
}

// 手机号登录
async function handlePhoneLogin() {
  if (!form.phone) {
    uni.showToast({
      title: role.value === 'user' ? '请输入手机号' : '请输入用户名',
      icon: 'none',
    })
    return
  }

  if (!form.password) {
    uni.showToast({
      title: '请输入密码',
      icon: 'none',
    })
    return
  }

  try {
    // 这里应该调用实际的登录接口
    console.log('手机号登录:', form)

    // 模拟登录成功，默认以业主身份登录
    await userStore.login({
      username: form.phone,
      password: form.password,
    }, role.value)

    uni.showToast({
      title: '登录成功',
      icon: 'success',
    })

    // 跳转到首页
    const url = role.value === 'user' ? '/pages/user/index' : '/pages/admin/index'

    setTimeout(() => {
      uni.switchTab({
        url,
        fail: (err) => {
          console.log('switchTab fail, trying navigateTo', err)
          uni.navigateTo({
            url,
            fail: (e) => {
              console.error(`跳转失败，请检查页面路径 ${url} 是否正确`, e)
            },
          })
        },
      })
    }, 1000)
  }
  catch (error) {
  }
}

// 微信登录
async function handleWechatLogin() {
  try {
    // 这里应该调用微信登录接口
    console.log('微信登录')

    // 模拟登录成功
    userStore.login(role.value)

    uni.showToast({
      title: '登录成功',
      icon: 'success',
    })

    // 跳转到首页
    const url = role.value === 'user' ? '/pages/user/index' : '/pages/admin/index'

    setTimeout(() => {
      uni.switchTab({
        url,
        fail: (err) => {
          console.log('switchTab fail, trying navigateTo', err)
          uni.navigateTo({
            url,
            fail: (e) => {
              console.error(`跳转失败，请检查页面路径 ${url} 是否正确`, e)
            },
          })
        },
      })
    }, 1000)
  }
  catch (error) {
    console.error('微信登录失败:', error)
    uni.showToast({
      title: '登录失败，请重试',
      icon: 'none',
    })
  }
}

// 返回上一页
function goBack() {
  uni.navigateBack()
}

// 查看服务条款
function viewServiceTerms() {
  uni.showToast({
    title: '查看服务条款',
    icon: 'none',
  })
}

// 查看隐私政策
function viewPrivacyPolicy() {
  uni.showToast({
    title: '查看隐私政策',
    icon: 'none',
  })
}

// 切换角色
function handleSwitchRole() {
  role.value = role.value === 'user' ? 'admin' : 'user'
}

// 注册
function handleRegister() {
  console.log('handleRegister')
  uni.showToast({
    title: '注册成功，请登录',
    icon: 'none',
  })
}
</script>

<template>
  <view class="login-container">
    <wd-navbar
      title="" :bordered="false" :safe-area-inset-top="true" left-arrow
      :custom-class="role === 'admin' ? 'admin-navbar' : 'user-navbar'" @click-left="goBack"
    />

    <!-- 顶部背景区域 -->
    <view class="header-section" :class="{ 'admin-theme': role === 'admin' }">
      <!-- 欢迎文字 -->
      <view class="welcome-text">
        <view class="mb-1 text-xl text-white font-bold">
          {{ role === 'admin' ? '管理员' : '业主' }}你好
        </view>
        <view class="text-base text-white opacity-90">
          欢迎使用{{ role === 'admin' ? '管理系统' : '业主服务' }}~
        </view>
      </view>

      <!-- 登录/注册切换按钮 -->
      <view class="mode-tabs">
        <view class="tab-btn" :class="{ active: currentMode === 'login' }" @click="switchMode('login')">
          登录
        </view>
        <view class="tab-btn" :class="{ active: currentMode === 'register' }" @click="switchMode('register')">
          注册
        </view>
      </view>
    </view>

    <!-- 表单区域 -->
    <view class="form-section">
      <!-- 手机号输入 -->
      <view class="input-group">
        <view class="input-label">
          <text v-if="role === 'user'">
            手机号
          </text>
          <text v-else>
            用户名
          </text>
        </view>
        <wd-input
          v-model="form.phone" :placeholder="role === 'user' ? '输入手机号' : '输入用户名'" type="number" :maxlength="11"
          class="custom-input"
        />
      </view>

      <!-- 密码输入 -->
      <view v-if="currentMode === 'login'" class="input-group">
        <view class="input-label">
          密码
        </view>
        <view class="pwd-input-row">
          <wd-input
            v-model="form.password" placeholder="请输入密码" type="safe-password" :maxlength="16"
            class="verify-input"
          />
        </view>
      </view>

      <view v-if="currentMode === 'register'" class="input-group">
        <view class="input-label">
          验证码
        </view>
        <view class="pwd-input-row">
          <wd-input v-model="form.verifyCode" placeholder="请输入验证码" type="number" :maxlength="6" class="verify-input">
            <template #suffix>
              <wd-button
                type="primary" size="small"
                :custom-class="`get-code-btn ${role === 'admin' ? 'admin-code-btn' : 'user-code-btn'}`"
                :disabled="countdown > 0" @click="sendVerifyCode"
              >
                <span v-if="countdown === 0" class="text-sm">
                  获取验证码
                </span>
                <span v-else class="text-sm">
                  {{ countdown }} s
                </span>
              </wd-button>
            </template>
          </wd-input>
        </view>
      </view>

      <!-- 注册按钮 -->
      <view v-if="currentMode === 'register'" class="login-btn-wrapper">
        <wd-button
          type="primary" size="large"
          :custom-class="`login-btn w-full ${role === 'admin' ? 'admin-btn' : 'user-btn'}`" @click="handleRegister"
        >
          注册
        </wd-button>
        <view class="mt-2 flex items-center justify-center">
          <text class="switch-role-link text-sm" :class="{ 'admin-link': role === 'admin' }" @click="handleSwitchRole">
            {{ role === 'user' ? '切换管理员注册' : '切换业主注册' }}
          </text>
        </view>
      </view>

      <template v-else>
        <!-- 登录按钮 -->
        <view class="login-btn-wrapper">
          <wd-button
            type="primary" size="large"
            :custom-class="`login-btn w-full ${role === 'admin' ? 'admin-btn' : 'user-btn'}`" @click="handlePhoneLogin"
          >
            登录
          </wd-button>
        </view>
        <!-- 微信登录按钮 -->
        <view class="wechat-btn-wrapper">
          <wd-button type="primary" size="large" custom-class="wechat-btn w-full mt-2" @click="handleWechatLogin">
            微信一键登录
          </wd-button>
        </view>
        <view class="mt-2 flex items-center justify-center">
          <text class="switch-role-link text-sm" :class="{ 'admin-link': role === 'admin' }" @click="handleSwitchRole">
            {{ role === 'user' ? '切换管理员登录' : '切换业主登录' }}
          </text>
        </view>
      </template>

      <!-- 服务条款 -->
      <view class="terms-section flex items-center justify-center">
        <wd-checkbox v-model="agree" @change="handleAgreeChange">
          <text class="terms-text">
            已阅读并同意
            <text class="link-text" :class="{ 'admin-link': role === 'admin' }" @click="viewServiceTerms">
              《服务条款》
            </text>
            和
            <text class="link-text" :class="{ 'admin-link': role === 'admin' }" @click="viewPrivacyPolicy">
              《隐私权政策》
            </text>
          </text>
        </wd-checkbox>
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.login-container {
  min-height: 100vh;
  background-color: #fff;
}

.header-section {
  padding: 26rpx 60rpx;
  position: relative;
  background: linear-gradient(180deg, #4a7fff 0%, #6b8eff 100%);
  transition: background 0.3s ease;

  &.admin-theme {
    background: linear-gradient(180deg, #ff6b35 0%, #ff8f65 100%);
  }
}

.welcome-text {
  padding-top: 50rpx;
  padding-bottom: 50rpx;
  font-size: 44rpx;
}

.mode-tabs {
  display: flex;
  justify-content: center;
  gap: 80rpx;
}

.tab-btn {
  color: rgba(255, 255, 255, 0.7);
  font-size: 32rpx;
  font-weight: 500;
  padding: 10rpx 20rpx;
  transition: all 0.3s;
}

.tab-btn.active {
  color: white;
  font-weight: bold;
  border-bottom: 4rpx solid white;
}

.form-section {
  background: white;
  border-radius: 40rpx 40rpx 0 0;
  padding: 60rpx 40rpx 80rpx;
  flex: 1;
  margin-top: 20rpx;
}

.input-group {
  margin-bottom: 40rpx;
}

.input-label {
  color: #333;
  font-size: 32rpx;
  font-weight: 500;
  margin-bottom: 20rpx;
}

.custom-input {
  background: #fff;
  border: 2rpx solid #e5e5e5;
  border-radius: 8rpx;
}

:deep(.custom-input .wd-input__inner) {
  padding: 26rpx 24rpx;
  font-size: 32rpx;
  color: #333;
}

:deep(.verify-input .wd-input__inner) {
  padding: 26rpx 24rpx;
  font-size: 32rpx;
  color: #333;
}

.verify-code-row {
  display: flex;
  gap: 2rpx;
  align-items: center;
  border: 2rpx solid #e5e5e5;
  border-radius: 8rpx;
  overflow: hidden;
}

.verify-input {
  flex: 1;
  background: #fff;
  border: none;
}

.get-code-btn {
  background: #4a7fff;
  color: white;
  padding: 22rpx 24rpx;
  font-size: 28rpx;
  white-space: nowrap;
  transition: all 0.3s;
  border: none;

  &.admin-code-btn {
    background: #ff6b35;
  }

  &.user-code-btn {
    background: #4a7fff;
  }

  &.disabled {
    background: #ccc;
    color: #999;
  }
}

.login-btn {
  width: 100%;
  margin: 60rpx 0 30rpx;
  background: #4a7fff;
  border-radius: 50rpx;
  height: 96rpx;
  font-size: 32rpx;
  font-weight: bold;
  transition: background-color 0.3s ease;

  &.admin-btn {
    background: #ff6b35;
  }

  &.user-btn {
    background: #4a7fff;
  }
}

.wechat-btn {
  width: 100%;
  margin-bottom: 40rpx;
  background: #07c160;
  border-radius: 50rpx;
  height: 96rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.terms-section {
  display: flex;
  align-items: flex-start;
  gap: 16rpx;
  margin-top: 40rpx;
}

.terms-text {
  color: #666;
  font-size: 24rpx;
  line-height: 1.5;
}

.link-text {
  color: #4a7fff;
  text-decoration: underline;
  transition: color 0.3s ease;

  &.admin-link {
    color: #ff6b35;
  }
}

.switch-role-link {
  color: #4a7fff;
  transition: color 0.3s ease;

  &.admin-link {
    color: #ff6b35;
  }
}

:deep(.wd-navbar) {
  background-color: #4a7fff;
  transition: background-color 0.3s ease;

  &.admin-navbar {
    background-color: #ff6b35;
  }

  &.user-navbar {
    background-color: #4a7fff;
  }
}

:deep(.wd-navbar__arrow) {
  color: #fff;
}
</style>
